package com.kingdee.pda.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;

import com.example.basecommon.http.RequestErrorHelper;
import com.example.basecommon.utils.MusicUtils;
import com.example.basecommon.utils.ScannerDialog;
import com.kingdee.pda.MyApplication;
import com.kingdee.pda.R;
import com.kingdee.pda.ui.dialog.LoadDialog;
import com.kingdee.pda.util.KeyboardUtils;
import com.kingdee.pda.util.LanguageUtil;
import com.trello.rxlifecycle2.components.support.RxFragmentActivity;

import butterknife.ButterKnife;

/**
 * Created by zhanlg
 * DATE 2018/4/4
 * TIME 16:07
 */

public abstract class BaseActivity extends RxFragmentActivity {

    private MyNetworkReceiver mNetworkReceiver;
    protected LoadDialog loadDialog;
    private RequestErrorHelper requestErrorHelper;
    public EditText focusEditText;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LanguageUtil.setLocale(this);
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
//        hideNavigationBarLayout();
        onActivityCreate(savedInstanceState);
        MyApplication.getInstance().addActivity(this);
        //设置竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //绑定ButterKnife
        ButterKnife.bind(this);

        loadDialog = new LoadDialog(this);
        initView();
        initData();

        requestErrorHelper = new RequestErrorHelper(this);

    }

    /**
     * 设置扫码监听
     *
     * @param editText
     */
    public void setEditTextScannerEvents(final EditText editText, View.OnKeyListener listener) {
        editText.setOnKeyListener(listener);

        editText.setOnLongClickListener(v -> {
            new ScannerDialog(BaseActivity.this,
                    result -> {
                        if (!TextUtils.isEmpty(result)) {
                            editText.setText(result);
                            editText.selectAll();
                            editText.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER));
                        }
                    }).config().show(v);
            return false;
        });
        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    focusEditText = editText;
                }
                editText.setBackgroundResource(b ? R.drawable.shape_bg_edit_selected : R.drawable.dialog_edit_bg);

            }
        });
    }


    public void showLoadingDialog() {
        KeyboardUtils.closeSoftKeybord(this);
        showLoadingDialog("Loading", false);
    }

    public void showLoadingDialog(String content, boolean cancelable) {
        if (loadDialog != null && !loadDialog.isShowing() && !isDestroyed()) {
            loadDialog.show();
            loadDialog.setTextView(content);
//            loadDialog.content(content);
        }
    }

    public void showLoadingDialog(int strId, boolean cancelable) {
        showLoadingDialog(getResources().getString(strId), cancelable);
    }

    public void dismissLoadingDialog() {
        if (loadDialog != null && loadDialog.isShowing()) {
            loadDialog.dismiss();
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
//            hideNavigationBarLayout();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        registNetworkReceiver();
        if (requestErrorHelper != null) {
            requestErrorHelper.resume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unRegistNetworkReceiver();
        if (requestErrorHelper != null) {
            requestErrorHelper.pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.getInstance().removeActivity(this);
        if (requestErrorHelper != null) {
            requestErrorHelper.destroy();
        }
        try {
            System.gc();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    private void hideNavigationBarLayout() {
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            final View decorView = getWindow().getDecorView();
            final int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(uiOptions);
            decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
                @Override
                public void onSystemUiVisibilityChange(int visibility) {
                    if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                        decorView.setSystemUiVisibility(uiOptions);
                    }
                }
            });
        }
    }


    protected abstract void onActivityCreate(Bundle savedInstanceState);

    protected abstract void initView();

    protected abstract void initData();

    protected abstract void onNetworkAvailable();

    protected abstract void onNetworkError();


    public class MyNetworkReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            /** 判断当前的网络连接状态是否可用 */
            if (intent == null || intent.getAction() == null) {
                return;
            }
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo info = connectivityManager.getActiveNetworkInfo();
                if (info != null && info.isAvailable()) {
                    //当前网络状态可用
                    int netType = info.getType();
                    if (netType == ConnectivityManager.TYPE_WIFI) {
                        //当前网络状态为-wifi
                        onNetworkAvailable();
                    } else if (netType == ConnectivityManager.TYPE_MOBILE) {
                        //当前网络状态为-mobile
                        onNetworkAvailable();
                    }
                } else {
                    //当前网络不可用
                    onNetworkError();
                }
            }
        }
    }

    private void registNetworkReceiver() {
        if (mNetworkReceiver == null) {
            mNetworkReceiver = new MyNetworkReceiver();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mNetworkReceiver, intentFilter);
    }

    private void unRegistNetworkReceiver() {
        if (mNetworkReceiver != null) {
            unregisterReceiver(mNetworkReceiver);
        }
    }


}
